package com.df.tv.launcher.view;

import java.net.URLDecoder;
import java.util.List;
import java.util.Random;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.df.tv.launcher.R;

import com.df.tv.launcher.LauncherApplication;
import com.df.tv.launcher.entity.FileInfo;
import com.df.tv.launcher.entity.HomeNavigationData;
import com.df.tv.launcher.params.AppTest;
import com.df.tv.launcher.params.ComParams;
import com.df.tv.launcher.util.FileAccess;
import com.df.tv.launcher.util.JsonParseUtil;
import com.df.tv.launcher.util.TmsGetFileTask;
import com.df.tv.launcher.util.TmsGetFileTask.onTmsGetFile;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.telecom.tv189.comlib.net.XHttpClient;
import com.telecom.tv189.comlib.net.json.entity.BaseEntity;
import com.telecom.tv189.comlib.util.Log;

/**
 * 首页导航View
 * 
 * @author John
 */
public class HomeNavigationView extends FrameLayout implements OnClickListener, OnFocusChangeListener {

    private static final String TAG = "HomeNavigationView";

    private static final String CACHE_FILE = "navigation.json";
    private static final int NAVIGATION_FILE = 6;

    private LayoutInflater inflater;
    private LinearLayout view;
    private Context context;

    private OnItemClickedListener onItemClickListener = null;

    private int textSizeNormal;
    private int textSizeBig;
    private int textOffset;

    public HomeNavigationView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context);
    }

    public HomeNavigationView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public HomeNavigationView(Context context) {
        super(context);
        initView(context);
    }

    private TextView newNavTextView(HomeNavigationData data) {
        TextView tv = new TextView(getContext());
        String titleStr = "??";
        try {
            titleStr = URLDecoder.decode(data.getTitle(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        tv.setText(titleStr);
        // 让动态添加的textview内容居中
        tv.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSizeNormal);
        tv.setSingleLine();
        tv.setClickable(true);
        tv.setFocusable(true);
        tv.setOnClickListener(this);
        tv.setTag(data);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(textSizeNormal * titleStr.length() + textOffset,
                LinearLayout.LayoutParams.MATCH_PARENT);
        tv.setLayoutParams(lp);
        tv.setOnFocusChangeListener(this);
        return tv;
    }

    public void initView(Context context) {
        this.context = context;
        textSizeNormal = this.context.getResources().getDimensionPixelSize(R.dimen.navTextSizeNormal);
        textSizeBig = this.context.getResources().getDimensionPixelSize(R.dimen.navTextSizeBig);
        textOffset = this.context.getResources().getDimensionPixelSize(R.dimen.navTextOffset);
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = (LinearLayout) inflater.inflate(R.layout.navigation_view, null);
        addView(view);

        loadNavigationData();
    }

    private void setNavigationView(List<HomeNavigationData> data) {
        // json
        for (HomeNavigationData d : data)
            view.addView(newNavTextView(d));

        HomeNavigationData d;
        // 首页textview
        d = new HomeNavigationData();
        d.setTitle(getContext().getResources().getString(R.string.navigation_homepage));
        d.setType("sy");
        view.addView(newNavTextView(d), 0);
        // 应用textview
        d = new HomeNavigationData();
        d.setTitle(getContext().getResources().getString(R.string.navigation_application));
        d.setType("yy");
        view.addView(newNavTextView(d));
        // 设置textview
        d = new HomeNavigationData();
        d.setTitle(getContext().getResources().getString(R.string.navigation_setting));
        d.setType("sz");
        view.addView(newNavTextView(d));
    }

    // 动态添加的TextView的点击事件
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (onItemClickListener != null) {
            onItemClickListener.onClick(v, id);
        }
    }

    // 回调
    public interface OnItemClickedListener {
        public void onClick(View v, int id);
    }

    public OnItemClickedListener getOnItemClickListener() {
        return onItemClickListener;
    }

    public void setOnItemClickListener(OnItemClickedListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    // 导航区字体获得焦点的事件
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        TextView tv = (TextView) v;
        if (hasFocus) {
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSizeBig);
            tv.setTextColor(Color.WHITE);
        }
        else {
            tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSizeNormal);
            tv.setTextColor(v.getContext().getResources().getColor(android.R.color.secondary_text_dark));
        }
    }

    /**
     * 得到服务器的json
     * 
     * @param tx
     * @param path
     * @param token
     */
    public void loadNavigationData() {
        //		final UserInfo user = UserInfoKeeper.getInstance().getInfo();
        //		if (user == null || TextUtils.isEmpty(user.getToken())) {
        //			loadNavDataFromLoacl();
        //			return;
        //		}
        new TmsGetFileTask(new onTmsGetFile() {
            @Override
            public void onTaskToResult(BaseEntity<FileInfo> baseEntity) {
                String uriPath = null;
                try {
                    uriPath = baseEntity.getInfo().getUrl();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    uriPath = (uriPath == null ? ComParams.NAV_ITEM_PATH : uriPath);
                }
                //				RequestParams requestParams = XHttpParamsUtil.getInstance().getIndex(user.getToken(), uriPath);
                XHttpClient.getInstance().get(
                        "http://211.149.200.227:30104/info.php?type=navigation&ggg=" + new Random().nextInt(10000000),
                        null, new RequestCallBack<String>() {
                            @Override
                            public void onStart() {
                                Log.d(this.getRequestUrl());
                            }

                            @Override
                            public void onFailure(HttpException arg0, String arg1) {
                                loadNavDataFromLoacl();
                            }

                            @Override
                            public void onSuccess(ResponseInfo<String> arg0) {
                                try {
                                    Log.i(TAG, arg0.result);
                                    setNavigationView(getJsonData(arg0.result));
                                    FileAccess.writeDataToFile(context, CACHE_FILE, arg0.result);// 存入sd卡
                                    return;
                                } catch (NullPointerException e) {
                                    e.printStackTrace();
                                } catch (JsonSyntaxException e) {
                                    e.printStackTrace();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                loadNavDataFromLoacl();
                            }
                        });
            }
        }).execute(String.valueOf(NAVIGATION_FILE));
    }

    private void loadNavDataFromLoacl() {
        try {
            String navigation_json = FileAccess.getFileData(context, CACHE_FILE);
            if (!TextUtils.isEmpty(navigation_json)) {
                setNavigationView(getJsonData(navigation_json));
                return;
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        loadNavDataFromAssets();
    }

    private List<HomeNavigationData> getJsonData(String json) {
        return JsonParseUtil.getInstance().getNavigationData(json).getInfo();
    }

    /**
     * 得到assets解析的数据
     * 
     * @return
     */
    private void loadNavDataFromAssets() {
        try {
            String json = FileAccess.getTestDataFromAssets(LauncherApplication.getInstance(),
                    AppTest.HOME_NAVIGATION_JSON_TEST);
            Gson gson = new Gson();
            List<HomeNavigationData> data = gson.fromJson(json, new TypeToken<List<HomeNavigationData>>() {}.getType());
            setNavigationView(data);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
